#This script is used to get infomation of a student, including score, chosen classes and picture
#Note: student score can be seen by only knowing school number, but student picture require local CDUT network and chosen classes require student password.
import re
import urllib
import urllib2
import cookielib
class Student:
#define some values
    schoolNo = ''
    password = ''
    #store cookies
    cookie = cookielib.CookieJar()  
    opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
    #store urls
    picUrl = ''
    scoreUrl = ''
    ChosenClassesUrl = ''
    loginUrl = ''
    
    def __init__(self, schoolNumber, pwd = ''):
        self.schoolNo = schoolNumber
        self.password = pwd
        self.loginUrl = 'http://202.115.139.16/login.php'
        self.ChosenClassesUrl = 'http://202.115.139.16/sel_listsys/sel_listsys.php'
        self.scoreUrl = 'http://202.115.139.16/xtcx_stu/stucj.php?xh='+self.schoolNo
        self.picUrl = 'http://202.115.130.240/zxs_zp//'+self.schoolNo[0:4]+'//'+self.schoolNo+'.jpg'
        self.logedin = 0;

    def login(self):
        loginInfo = {
                'upwd':self.password,
                'uname':self.schoolNo,
                'usertype':'%D1%A7%C9%FA'
                }
        urlInfo = 'upwd='+self.password+'&uname='+self.schoolNo+'&usertype=%D1%A7%C9%FA'
        #open connection to get cookie
        #self.opener.addheaders[('User-Agent','Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 FBSMTWB')]
        f = self.opener.open(self.loginUrl,urlInfo)
        if len(f.read()) < 700:
            #login failed
            return 0 
        else:
            return 1



        

    
    def getChosenClasses(self):

        pageBuffer = self.opener.open(self.ChosenClassesUrl).read()
        pageBuffer_unicode = pageBuffer.decode('gb2312')    #Transfer to 
        assert(pageBuffer_unicode == pageBuffer_unicode)
        return pageBuffer_unicode   #debug

    def getRXClasses(self):
        classBuffer = self.getChosenClasses()
        pattern = re.compile(r'RX\d{8}</td><td>.*(?=</td><td>\d{2}<)')
        match = pattern.findall(classBuffer)
        if match:
            for index in range (0, len(match)):
                print match[index][0:10]+" "+match[index][20:]
        else:
            print 'You don\'t have RX classes'



        


    def getScore(self):
#This function gonna return an html file of score
        pageBuffer = urllib.urlopen(self.scoreUrl).read()
        pageBuffer_unicode = pageBuffer.decode('gb2312')    #Transfer to 
        assert(pageBuffer_unicode == pageBuffer_unicode)
        return pageBuffer_unicode


    def getPic(self):
        print("get Picture")

    def getLibPic(self):
        pass
        


